package com.orange.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerModel {

	private Configuration configuration = null;  
	
	public FreeMarkerModel() {
		configuration = new Configuration();  
		configuration.setDefaultEncoding("utf-8"); 
	}
	
	 /**
     * 二级指标细则内容导出模板
     * @param dataMap
     * @param fileName
     * @throws UnsupportedEncodingException
     */
    public void createDoc1(HttpServletRequest request,HttpServletResponse res,Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {  
        //dataMap 要填入模本的数据文件  
        //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，  
        //这里我们的模板是放在template包下面  
        configuration.setClassForTemplateLoading(this.getClass(), "/com/orange/file");  
        Template t = null;
		try {
			// test.ftl为要装载的模板

			t = configuration.getTemplate("moban.ftl");
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 输出文档路径及名称,这个路径是文档在服务器中的路径
		String localName = "f:/dataAuth"+"/file"+"/"+dataMap.get("schoolId");
		File f = new File(localName);
		if(!f.exists()){
			f.mkdirs();
		}
		File outFile = new File(localName+"/"+fileName);
		if (!outFile.exists()) {
			try {
				outFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			FileOutputStream fos = new FileOutputStream(outFile);
			OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
			Writer out = new BufferedWriter(oWriter);
			t.process(dataMap, out);
			out.close();
			fos.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(outFile));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    }
    
   
}
